<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<!-- 组合式API 计算属性 -->

<body>
    <div id="app">

    </div>
</body>
<script src="js/vue.js"></script>
<script>

    const app = Vue.createApp({
        setup(props, context) {
            const { ref, computed } = Vue;

            let num = ref(10);

            // 计算属性的 get 与 set
            let num1 = computed({
                get: () => {
                    console.log("-------computed:get---------");
                    return num.value * 10;
                },
                set: (res) => {
                    console.log("-------computed:set---------");
                    console.log(res)
                    num.value = res;    // set 值的时候，不能变更 num1 的值，这样子会导致递归赋值，内存溢出
                }
            });

            setTimeout(() => {
                num1.value = 200;   // 两秒钟之后，修改计算属性的值
            }, 2000);

            const add = () => {
                console.log("-------add------");
                return num.value += 10;
            };

            return {
                num, num1, add
            }
        },
        template: `
            <div>
                <p>原始值：{{num}}</p>
                <p>计算属性：{{num1}}</p>
                <p>计算属性：{{num1}}</p>
                <p>计算属性：{{num1}}</p>
                <p>计算属性：{{num1}}</p>
                <p>-----------------------</p>
                <button @click="add">点击</button>
            </div>
        `
    }).mount("#app");

</script>

</html>